package com.coin900.coin.server;

import com.coin900.coin.base.AjaxResponse;
import com.coin900.coin.base.Constants;
import com.coin900.coin.base.FuConstants;
import com.coin900.coin.base.utils.StringEscapeEditor;
import com.coin900.coin.persist.fu.FuUserVO;
import com.value.mybatis.DaoRouter;
import com.value.utils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Value
 * <p/>
 * Copyright (c) 2012 Value ValueSoft Inc., All rights reserved.
 * <p/>
 * This software is the confidential and proprietary information of
 * ValueSoft Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with ValueSoft.com.
 * <p/>
 * Revision History
 * Date      		Programmer       Notes
 * 13-10-15   	     laborc		     Initial
 * *********************************************************************
 */
public abstract class BaseController {
    private static final Log logger = LogFactory.getLog(BaseController.class);


    protected void setParams(ModelAndView view) {
    }

    /**
     * 创建视图
     *
     * @param ftl
     * @return
     */
    protected ModelAndView buildView(HttpServletRequest request, String ftl) {
        String serverName = request.getServerName();
        if (serverName.startsWith("wap")) {
            ftl = "mobile/" + ftl;
        }
        ModelAndView view = new ModelAndView(ftl);
        try {
            view.addObject("spmout", Constants.spmout);
            view.addObject("env", Constants.env);
            view.addObject("domAjax", Constants.domAjax);
            view.addObject("servletPath", request.getServletPath());
            view.addObject("sysDate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
            view.addObject("isLogin", getUser() != null);
            view.addObject("bucketDomain", FuConstants.BUCKET_DOMAIN);
            view.addObject("pBucketDomain", FuConstants.P_BUCKET_DOMAIN);
            FuUserVO user = getUser();
            if (user != null) {
                view.addObject("username", user.getUsername());
                view.addObject("portrait", user.getPortrait());
                view.addObject("userId", user.getId());
                view.addObject("googleStatus", user.getGoogleStatus());
                view.addObject("googleStatus", user.getGoogleStatus());
                view.addObject("mobileStatus", user.getMoblieStatus());
                view.addObject("emailStatus", user.getEmailStatus());

            }
            this.setParams(view);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }

    protected AjaxResponse buildAjaxResponse(HttpServletRequest request) {
        AjaxResponse response = new AjaxResponse(request, getJsonPath());
        return response;
    }

    /**
     * 构建异常编号
     *
     * @param request
     * @return
     */
    protected String buildErrorCode(HttpServletRequest request) {
        String path = request.getRequestURI().substring(request.getContextPath().length());
        path = path.substring(1);
        path = path.replace("/", ".");
        String method = request.getParameter("_method");
        if (StringUtils.isBlank(method)) {
            method = request.getMethod();
        }
        return path + ":" + method.toLowerCase();
    }


    protected String decode(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        String target = "";
        try {
            target = URLDecoder.decode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        return target;
    }

    protected String getJsonPath() {
        return "";
    }

    protected FuUserVO getUser() {
        FuUserVO user = (FuUserVO) this.getAttribute("user");
        return user;
    }

    protected void setUser(FuUserVO user) {
        this.setAttribute("user", user);
    }


    /**
     * 取得session
     */
    protected Session getSession() {
        Subject currentUser = SecurityUtils.getSubject();
        return currentUser.getSession();
    }

    /**
     * 取得session
     */
    protected Session getSession(boolean create) {
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession(create);
        return session;
    }

    protected void setAttribute(Object key, Object value) {
        Session session = this.getSession(false);
        if (session != null) {
            session.setAttribute(key, value);
        }
    }

    protected Object getAttribute(String key) {
        Session session = this.getSession(false);
        if (session != null) {
            return session.getAttribute(key);
        }
        return null;
    }


    protected String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null) {
            String[] ipSplit = StringUtils.split(ip, ",");
            if (ipSplit.length > 1) {
                ip = ipSplit[0];
            }
        }
        return ip;
    }


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(String.class, new StringEscapeEditor(true, true, true));
    }


    @Autowired
    private DaoRouter daoRouter;


}
